package com.ruoyi.web.controller.business.customer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.customer.domain.*;
import com.ruoyi.business.customer.domain.dto.JbCustomerDto;
import com.ruoyi.business.customer.domain.dto.JbCustomerListDto;
import com.ruoyi.business.customer.domain.dto.JbCustomerTransferDto;
import com.ruoyi.business.customer.domain.dto.JbCustomerUpdateDto;
import com.ruoyi.business.customer.domain.vo.*;
import com.ruoyi.business.customer.service.JbCustomerFastSearchService;
import com.ruoyi.business.customer.service.JbCustomerService;
import com.ruoyi.business.customer.service.JbFavoriteTableService;
import com.ruoyi.business.order.domain.JbOrder;
import com.ruoyi.common.annotation.BusinessOperLog;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessErrorEnum;
import com.ruoyi.common.enums.BusinessOperModule;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.RoleEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.controller.system.factory.SysDataScopeFactory;
import com.ruoyi.web.core.JoR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 客户 Controller
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Api("客户")
@RestController
@RequestMapping("/customer")
public class JbCustomerController extends BaseController
{
    @Autowired
    private JbCustomerService service;
    @Autowired
    private JbFavoriteTableService jbFavoriteTableService;
    @Autowired
    private SysDataScopeFactory sysDataScopeFactory;
    @Autowired
    private JbCustomerFastSearchService jbCustomerFastSearchService;

    /**
     * 查询客户列表
     */
    @ApiOperation("查询客户列表")
    @PreAuthorize("@ss.hasPermi('customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(PageParam page, JbCustomerListDto jbCustomerListDto)
    {
        jbCustomerListDto.setDataType(Constants.PUBLIC_NUMBER_0);
        IPage<JbCustomerListVo> iPage = service.seniorListData(page, jbCustomerListDto);
        return JoR.getDataTable(iPage);
    }

    /**
     * 查询全部客户列表
     */
    @ApiOperation("查询全部客户列表")
//    @PreAuthorize("@ss.hasPermi('customer:allList')")
    @GetMapping("/allList")
    public TableDataInfo allList(JbCustomer jbCustomer)
    {
        LambdaQueryWrapper<JbCustomer> wrapper = Wrappers.lambdaQuery(jbCustomer);
        if (StringUtils.isNotBlank(jbCustomer.getCustomerName()))
        {
            wrapper.like(JbCustomer::getCustomerName, jbCustomer.getCustomerName());
            jbCustomer.setCustomerName(null);
        }
        //角色数据权限
        List<Long> roleData=sysDataScopeFactory.fnListDataScope(Constants.PUBLIC_NUMBER_0.toString());
        wrapper.in(ObjectUtils.isNotEmpty(roleData), JbCustomer::getBusinessManagerId, roleData);
        wrapper.orderByDesc(JbCustomer::getId);

        return getDataTable(service.list(wrapper));
    }

    /**
     * 导出客户列表
     */
    @ApiOperation("导出客户列表")
    @PreAuthorize("@ss.hasPermi('customer:export')")
    @Log(title = "客户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PageParam page, JbCustomer jbCustomer)
    {
        LambdaQueryWrapper<JbCustomer> select = new LambdaQueryWrapper<>();
        IPage<JbCustomer> iPage = service.page(page.b(), select);
        iPage.getRecords().forEach(item -> item.setPhoneDesensitized(item));
        List<JbCustomer> list = iPage.getRecords();
        ExcelUtil<JbCustomer> util = new ExcelUtil<JbCustomer>(JbCustomer.class);
        util.exportExcel(response, list, "客户数据");
    }

    /**
     * 获取客户详细信息
     */
    @ApiOperation("获取客户详细信息")
    @PreAuthorize("@ss.hasPermi('customer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        JbCustomer byId = service.getById(id);
        byId.setPhoneDesensitized(byId);
        return success();
    }

    /**
     * 新增客户
     */
    @ApiOperation("新增客户")
    @PreAuthorize("@ss.hasAnyPermi('customer:add,opportunity:becomeCustomer')")
    @Log(title = "新增客户", businessType = BusinessType.INSERT)
    @BusinessOperLog(title = "新增客户", businessType = BusinessType.INSERT, operModule = BusinessOperModule.CUSTOMER_OPER)
    @PostMapping
    public AjaxResult add(@RequestBody JbCustomerDto jbCustomerDto)
    {
        Long id = service.saveInfo(jbCustomerDto);
        if (ObjectUtils.isNotEmpty(id))
        {
            return AjaxResult.success(id);
        }
        return AjaxResult.error();
    }

    /**
     * 修改客户
     */
    @ApiOperation("修改客户")
    @PreAuthorize("@ss.hasPermi('customer:edit')")
    @Log(title = "修改客户", businessType = BusinessType.UPDATE)
    @BusinessOperLog(title = "修改客户", businessType = BusinessType.UPDATE, operModule = BusinessOperModule.CUSTOMER_OPER)
    @PutMapping
    public AjaxResult edit(@RequestBody JbCustomerUpdateDto jbCustomerUpdateDto)
    {
        return toAjax(service.updateInfoById(jbCustomerUpdateDto));
    }

    /**
     * 删除客户
     */
    @ApiOperation("删除客户")
    @PreAuthorize("@ss.hasPermi('customer:remove')")
    @Log(title = "删除客户", businessType = BusinessType.DELETE)
    @BusinessOperLog(title = "删除客户", businessType = BusinessType.DELETE, operModule = BusinessOperModule.CUSTOMER_OPER)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(service.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 客户查重
     */
    @ApiOperation("客户查重")
    @PreAuthorize("@ss.hasPermi('customer:customerIsExist')")
    @GetMapping(value = "/customerIsExist/{phoneNumber}")
    public AjaxResult customerIsExist(@PathVariable("phoneNumber") String phoneNumber)
    {
        // 查询订单这个客户是否有提交订单
        service.customerIsExist(phoneNumber);
        // 查询是否存在客户
        long count = service.count(new LambdaQueryWrapper<JbCustomer>().eq(JbCustomer::getPhoneNumber, phoneNumber));
        if (count > 0)
        {
            return AjaxResult.error(BusinessErrorEnum.CUSTOMER_CHECK_10001.getCode(), String.format(BusinessErrorEnum.CUSTOMER_CHECK_10001.getMsg(), count));
        }

        return success(count);
    }

    /**
     * 获取客户详细信息
     */
    @ApiOperation("获取客户详细信息")
    @PreAuthorize("@ss.hasPermi('customer:query')")
    @GetMapping(value = "/detailsInfo/{id}")
    public AjaxResult detailsInfo(@PathVariable("id") Long id)
    {
        return success(service.detailsInfo(id));
    }


    /**
     * 修改客户
     */
    @ApiOperation("修改成无效客户")
//    @PreAuthorize("@ss.hasPermi('customer:editNullityCustomer')")
    @Log(title = "修改成无效客户", businessType = BusinessType.UPDATE)
    @BusinessOperLog(title = "修改成无效客户", businessType = BusinessType.UPDATE, operModule = BusinessOperModule.CUSTOMER_OPER)
    @PutMapping("/invalidCustomer/{id}")
    public AjaxResult invalidCustomer(@PathVariable("id") Long id)
    {
        JbCustomer update = new JbCustomer();
        update.setId(id);
        update.setIsInvalid(Constants.PUBLIC_NUMBER_1);
        update.setDataType(Constants.PUBLIC_NUMBER_3);
        return toAjax(service.updateById(update));
    }

    /**
     * 修改置顶客户
     */
    @ApiOperation("修改置顶客户")
    @PreAuthorize("@ss.hasPermi('customer:editTopUp')")
    @Log(title = "修改置顶客户", businessType = BusinessType.UPDATE)
    @BusinessOperLog(title = "修改置顶客户", businessType = BusinessType.UPDATE, operModule = BusinessOperModule.CUSTOMER_OPER)
    @PutMapping("/editTopUp/{id}")
    public AjaxResult editTopUp(@PathVariable("id") Long id)
    {
        return toAjax(service.update(Wrappers.lambdaUpdate(JbCustomer.class).eq(JbCustomer::getId, id)
                .set(JbCustomer::getTopUpTime, new Date())));
    }
    /**
     * 取消置顶客户
     */
    @ApiOperation("取消置顶客户")
    @PreAuthorize("@ss.hasPermi('customer:editTopUp')")
    @Log(title = "取消置顶客户", businessType = BusinessType.UPDATE)
    @BusinessOperLog(title = "取消置顶客户", businessType = BusinessType.UPDATE, operModule = BusinessOperModule.CUSTOMER_OPER)
    @PutMapping("/cancelTopUp/{id}")
    public AjaxResult cancelTopUp(@PathVariable("id") Long id)
    {
        JbCustomer byId = service.getById(id);
        return toAjax(service.update(Wrappers.lambdaUpdate(JbCustomer.class).eq(JbCustomer::getId, id)
                .set(JbCustomer::getTopUp, null)
                .set(JbCustomer::getTopUpTime, byId.getCreateTime())));
    }

    @ApiOperation("我的客户-转移客户")
    @PreAuthorize("@ss.hasPermi('customer:transferCustomer')")
    @Log(title = "我的客户-转移客户", businessType = BusinessType.UPDATE)
    @BusinessOperLog(title = "我的客户-转移客户", businessType = BusinessType.UPDATE, operModule = BusinessOperModule.CUSTOMER_OPER)
    @PutMapping("/transferCustomer")
    public AjaxResult transferCustomer(JbCustomerTransferDto jbCustomerTransferDto)
    {
        jbCustomerTransferDto.setOpType(Constants.PUBLIC_NUMBER_0);
        jbCustomerTransferDto.setDataType(Constants.PUBLIC_NUMBER_0);
        return toAjax(service.transferCustomer(jbCustomerTransferDto));
    }

    @ApiOperation("移入公司公海")
    @PreAuthorize("@ss.hasPermi('customer:transferCompanyHighSeas')")
    @Log(title = "移入公司公海", businessType = BusinessType.UPDATE)
    @PutMapping("/transferCompanyHighSeas")
    public AjaxResult transferCompanyHighSeas(JbCustomerTransferDto jbCustomerTransferDto)
    {
        jbCustomerTransferDto.setDataType(Constants.PUBLIC_NUMBER_1);
        jbCustomerTransferDto.setDataTypeTime(new Date());
        return toAjax(service.transferHighSeas(jbCustomerTransferDto));
    }

    @ApiOperation("移入部门公海")
    @PreAuthorize("@ss.hasPermi('customer:transferDeptHighSeas')")
    @Log(title = "移入部门公海", businessType = BusinessType.UPDATE)
    @PutMapping("/transferDeptHighSeas")
    public AjaxResult transferDeptHighSeas(JbCustomerTransferDto jbCustomerTransferDto)
    {
        jbCustomerTransferDto.setDataType(Constants.PUBLIC_NUMBER_2);
        jbCustomerTransferDto.setDataTypeTime(new Date());
        return toAjax(service.transferHighSeas(jbCustomerTransferDto));
    }

    @ApiOperation("重点关注")
//    @PreAuthorize("@ss.hasPermi('customer:favorite')")
    @Log(title = "重点关注", businessType = BusinessType.UPDATE)
    @BusinessOperLog(title = "重点关注", businessType = BusinessType.UPDATE, operModule = BusinessOperModule.CUSTOMER_OPER)
    @PutMapping("/favorite/{customerId}")
    public AjaxResult favorite(@PathVariable("customerId") Long customerId)
    {
        long count = jbFavoriteTableService.count(Wrappers.lambdaQuery(JbFavoriteTable.class)
                .eq(JbFavoriteTable::getType, Constants.PUBLIC_NUMBER_2)
                .eq(JbFavoriteTable::getRelatedId, customerId));
        if (count > 0)
        {
            // 表示已经存在，则直接返回ture
            return toAjax(true);
        }
        JbFavoriteTable jbFavoriteTable = new JbFavoriteTable();
        Long userId = getUserId();
        jbFavoriteTable.setType(Constants.PUBLIC_NUMBER_2);
        jbFavoriteTable.setUserId(userId);
        jbFavoriteTable.setRelatedId(customerId);
        return toAjax(jbFavoriteTableService.save(jbFavoriteTable));
    }

    @ApiOperation("取消重点关注")
//    @PreAuthorize("@ss.hasPermi('customer:cancelFavorite')")
    @Log(title = "取消重点关注", businessType = BusinessType.UPDATE)
    @BusinessOperLog(title = "取消重点关注", businessType = BusinessType.UPDATE, operModule = BusinessOperModule.CUSTOMER_OPER)
    @PutMapping("/cancelFavorite/{id}")
    public AjaxResult cancelFavorite(@PathVariable("id") Long id)
    {
        return toAjax(jbFavoriteTableService.removeById(id));
    }

    /**
     * 客户360概况
     */
    @ApiOperation("客户360概况")
//    @PreAuthorize("@ss.hasPermi('customer:overViewInfo')")
    @GetMapping(value = "/overViewInfo/{id}")
    public AjaxResult overViewInfo(@PathVariable("id") Long id)
    {
        return success(service.overViewInfo(id));
    }

    /**
     * 查询客户动态列表
     */
    @ApiOperation("查询客户360动态列表")
//    @PreAuthorize("@ss.hasPermi('customer:customerDynamicList')")
    @GetMapping("/customerDynamicList")
    public TableDataInfo customerDynamicList(PageParam page, JbCustomerListDto jbCustomerListDto)
    {
        IPage<CustomerDynamicListVo> iPage = service.customerDynamicList(page.b(), jbCustomerListDto);
        return JoR.getDataTable(iPage);
    }

    @ApiOperation("客户360详细")
//    @PreAuthorize("@ss.hasPermi('customer:detailedInforMtion')")
    @GetMapping(value = "/detailedInforMtion/{id}")
    public AjaxResult detailedInforMtion(@PathVariable("id") Long id)
    {
        return success(service.detailedInforMtion(id));
    }

    @ApiOperation("客户360订单分析-月份统计")
//    @PreAuthorize("@ss.hasPermi('customer:orderAnalysisMonth')")
    @GetMapping(value = "/orderAnalysisMonth")
    public AjaxResult orderAnalysisMonth(Long id, String year, String orderBy)
    {
        return success(service.orderAnalysisMonth(id, Integer.parseInt(year), orderBy));
    }

    @ApiOperation("客户360订单分析-月份统计")
    @Log(title = "客户360订单分析-月份统计", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('customer:exportPrderAnalysisMonth')")
    @PostMapping(value = "/exportPrderAnalysisMonth")
    public void exportPrderAnalysisMonth(HttpServletResponse response, Long id, String year, String orderBy)
    {
        List<JbCustomerMonthStatistics> list = service.orderAnalysisMonth(id, Integer.parseInt(year), orderBy);
        ExcelUtil<JbCustomerMonthStatistics> util = new ExcelUtil<JbCustomerMonthStatistics>(JbCustomerMonthStatistics.class);
        util.exportExcel(response, list, "客户月份订单导出");
    }

    @ApiOperation("客户360订单分析-产品统计")
//    @PreAuthorize("@ss.hasPermi('customer:orderAnalysisProduct')")
    @GetMapping(value = "/orderAnalysisProduct")
    public TableDataInfo orderAnalysisProduct(Long id, String year, PageParam page)
    {
        IPage<JbCustomerProductStatistics> iPage = service.orderAnalysisProduct(id, year, page);
        return JoR.getDataTable(iPage);
    }

    @ApiOperation("客户360订单记录")
//    @PreAuthorize("@ss.hasPermi('customer:orderAnalysis')")
    @GetMapping(value = "/orderRecord")
    public TableDataInfo orderRecord(Long id, String year, PageParam page)
    {
        IPage<JbOrder> iPage = service.orderRecord(page.b(), id, year);
        return JoR.getDataTable(iPage);
    }

    @ApiOperation("客户360作物结构")
//    @PreAuthorize("@ss.hasPermi('customer:cropStructure')")
    @GetMapping(value = "/cropStructure/{id}")
    public AjaxResult cropStructure(@PathVariable("id") Long id)
    {
        return success(service.cropStructure(id));
    }

    /**
     * 导出作物或销售
     */
    @ApiOperation("导出商机列表")
//    @PreAuthorize("@ss.hasPermi('opportunity:export')")
    @Log(title = "商机", businessType = BusinessType.EXPORT)
    @PostMapping("/cropStructureExport")
    public void export(HttpServletResponse response, PageParam page, JbCustomerCropStructure jbCustomerCropStructure)
    {
        if (Constants.PUBLIC_NUMBER_1.equals(jbCustomerCropStructure.getCropType().intValue()))
        {
            List<JbCustomerCropStructureStatistics> jbCustomerCropStructureStatistics = service.cropStructure(jbCustomerCropStructure.getCustomerId());
            jbCustomerCropStructureStatistics.forEach(a ->
            {
                a.setCropYear(a.getCropYear() + "年");
                a.setPercentage(a.getPercentage() + "%");
            });
            ExcelUtil<JbCustomerCropStructureStatistics> util = new ExcelUtil<JbCustomerCropStructureStatistics>(JbCustomerCropStructureStatistics.class);
            util.exportExcel(response, jbCustomerCropStructureStatistics, "作物结构数据");
        } else if (Constants.PUBLIC_NUMBER_2.equals(jbCustomerCropStructure.getCropType().intValue()))
        {
            List<JbCustomerSalesStatistics> jbCustomerCropStructureStatistics = service.saleScale(jbCustomerCropStructure.getCustomerId());
            jbCustomerCropStructureStatistics.forEach(a ->
            {
                a.setCropYear(a.getCropYear() + "年");
                a.setPercentage(a.getPercentage() + "%");
            });
            ExcelUtil<JbCustomerSalesStatistics> util = new ExcelUtil<JbCustomerSalesStatistics>(JbCustomerSalesStatistics.class);
            util.exportExcel(response, jbCustomerCropStructureStatistics, "销售规模数据");
        }
    }

    @ApiOperation("客户360销售规模")
//    @PreAuthorize("@ss.hasPermi('customer:saleScale')")
    @GetMapping(value = "/saleScale/{id}")
    public AjaxResult saleScale(@PathVariable("id") Long id)
    {
        return success(service.saleScale(id));
    }

    /**
     * 查询无效客户列表
     */
    @ApiOperation("查询无效客户列表")
//    @PreAuthorize("@ss.hasPermi('customer:invalidList')")
    @GetMapping("/invalidList")
    public TableDataInfo invalidList(PageParam page, JbCustomerListDto jbCustomerListDto)
    {
        jbCustomerListDto.setIsInvalid(Constants.PUBLIC_NUMBER_1);
        jbCustomerListDto.setDataType(Constants.PUBLIC_NUMBER_3);
        IPage<JbCustomerListVo> iPage = service.listData(page.b(), jbCustomerListDto);
        return JoR.getDataTable(iPage);
    }

    @ApiOperation("无效客户-转移客户")
//    @PreAuthorize("@ss.hasPermi('customer:invalidTransferCustomer')")
    @Log(title = "无效客户-转移客户", businessType = BusinessType.UPDATE)
    @PutMapping("/invalidTransferCustomer")
    public AjaxResult invalidTransferCustomer(JbCustomerTransferDto jbCustomerTransferDto)
    {
        jbCustomerTransferDto.setOpType(Constants.PUBLIC_NUMBER_1);
        jbCustomerTransferDto.setDataType(Constants.PUBLIC_NUMBER_0);
        return toAjax(service.transferCustomer(jbCustomerTransferDto));
    }

    /**
     * 查询公司公海列表
     */
    @ApiOperation("查询公司公海列表")
//    @PreAuthorize("@ss.hasPermi('customer:companyHighSeasList')")
    @GetMapping("/companyHighSeasList")
    public TableDataInfo companyHighSeasList(PageParam page, JbCustomerListDto jbCustomerListDto)
    {
        jbCustomerListDto.setIsInvalid(Constants.PUBLIC_NUMBER_0);
        jbCustomerListDto.setDataType(Constants.PUBLIC_NUMBER_1);
        IPage<JbCustomerListVo> iPage = service.seniorListData(page, jbCustomerListDto);
        return JoR.getDataTable(iPage);
    }

    /**
     * 查询部门公海列表
     */
    @ApiOperation("查询部门公海列表")
//    @PreAuthorize("@ss.hasPermi('customer:deptHighSeasList')")
    @GetMapping("/deptHighSeasList")
    public TableDataInfo deptHighSeasList(PageParam page, JbCustomerListDto jbCustomerListDto)
    {
        jbCustomerListDto.setIsInvalid(Constants.PUBLIC_NUMBER_0);
        jbCustomerListDto.setDataType(Constants.PUBLIC_NUMBER_2);
        IPage<JbCustomerListVo> iPage = service.listData(page.b(), jbCustomerListDto);
        return JoR.getDataTable(iPage);
    }

    @ApiOperation("公司公海-转移客户")
//    @PreAuthorize("@ss.hasPermi('customer:companyTransferCustomer')")
    @Log(title = "公司公海-转移客户", businessType = BusinessType.UPDATE)
    @PutMapping("/companyTransferCustomer")
    public AjaxResult companyTransferCustomer(JbCustomerTransferDto jbCustomerTransferDto)
    {
        jbCustomerTransferDto.setOpType(Constants.PUBLIC_NUMBER_3);
        jbCustomerTransferDto.setDataType(Constants.PUBLIC_NUMBER_0);
        return toAjax(service.transferCustomer(jbCustomerTransferDto));
    }

    @ApiOperation("部门公海-领取客户")
//    @PreAuthorize("@ss.hasPermi('customer:deptTransferCustomer')")
    @Log(title = "部门公海-领取客户", businessType = BusinessType.UPDATE)
    @PutMapping("/deptTransferCustomer")
    public AjaxResult deptTransferCustomer(JbCustomerTransferDto jbCustomerTransferDto)
    {
        jbCustomerTransferDto.setOpType(Constants.PUBLIC_NUMBER_2);
        jbCustomerTransferDto.setDataType(Constants.PUBLIC_NUMBER_0);
        return toAjax(service.transferCustomer(jbCustomerTransferDto));
    }

    /**
     * 查询重点客户列表
     */
    @ApiOperation("查询重点客户列表")
//    @PreAuthorize("@ss.hasPermi('customer:favoriteCustomerList')")
    @GetMapping("/favoriteCustomerList")
    public TableDataInfo favoriteCustomerList(PageParam page, JbCustomerListDto jbCustomerListDto)
    {
        if (ObjectUtils.isEmpty(jbCustomerListDto.getBusinessManagerId()))
        {
            jbCustomerListDto.setBusinessManagerId(getUserId());
        }
        jbCustomerListDto.setDataType(Constants.PUBLIC_NUMBER_0);
        jbCustomerListDto.setCreateBy(getUserId());
        IPage<JbCustomerListVo> iPage = service.favoriteSeniorListData(page.b(), jbCustomerListDto);
        return JoR.getDataTable(iPage);
    }

    /**
     * 查询重点客户列表
     */
    @ApiOperation("查询客户归属记录")
//    @PreAuthorize("@ss.hasPermi('customer:belongToRecord')")
    @GetMapping("/belongToRecord/{id}")
    public TableDataInfo belongToRecord(@PathVariable("id") Long id, PageParam page)
    {
        JbCustomer jbCustomer = new JbCustomer();
        jbCustomer.setId(id);
        IPage<JbCustomerBelongToRecordVo> iPage = service.belongToRecord(page.b(), jbCustomer);
        return JoR.getDataTable(iPage);
    }

    /**
     * 查询设置筛选字段
     */
    @ApiOperation("查询设置筛选字段")
//    @PreAuthorize("@ss.hasPermi('customer:setFieldList')")
    @GetMapping("/setFieldList")
    public AjaxResult setFieldList()
    {
        return success(service.setFieldList());
    }

    /**
     * 添加和修改设置筛选字段
     */
    @ApiOperation("添加或修改设置字段")
//    @PreAuthorize("@ss.hasPermi('customer:setFieldSave')")
    @Log(title = "添加或修改设置字段", businessType = BusinessType.INSERT)
    @PostMapping("/setFieldSave")
    public AjaxResult setFieldSave(@RequestBody List<JbCustomerField> jbCustomerFields)
    {
        return toAjax(service.setFieldSave(jbCustomerFields));
    }

    /**
     * 快速设置添加
     */
    @ApiOperation("添加或修改设置字段")
//    @PreAuthorize("@ss.hasPermi('customer:setFieldSave')")
    @Log(title = "添加或修改设置字段", businessType = BusinessType.INSERT)
    @PostMapping("/fastSearchSave")
    public AjaxResult fastSearchSave(@RequestBody JbCustomerFastSearch jbCustomerFastSearch)
    {
        return toAjax(service.fastSearchSave(jbCustomerFastSearch));
    }

    /**
     * 查询设置快速设置
     */
    @ApiOperation("查询设置筛选字段")
//    @PreAuthorize("@ss.hasPermi('customer:fastSearchList')")
    @GetMapping("/fastSearchList")
    public AjaxResult fastSearchList()
    {
        return success(service.fastSearchList());
    }

    /**
     * 删除设置快速设置
     */
    @ApiOperation("删除设置快速设置")
//    @PreAuthorize("@ss.hasPermi('customer:fastSearchList')")
    @Log(title = "删除设置快速设置", businessType = BusinessType.DELETE)
    @DeleteMapping("/fastSearchDel/{id}")
    public AjaxResult fastSearchDel(@PathVariable("id") Long id)
    {
        return success(service.fastSearchDel(id));
    }

    /**
     * 快速设置天置顶
     */
    @ApiOperation("快速设置天置顶")
//    @PreAuthorize("@ss.hasPermi('customer:fastTopUp')")
    @Log(title = "快速设置天置顶", businessType = BusinessType.UPDATE)
    @PutMapping("/fastTopUp/{id}")
    public AjaxResult fastTopUp(@PathVariable("id") Long id)
    {
        return success(jbCustomerFastSearchService.update(Wrappers.lambdaUpdate(JbCustomerFastSearch.class)
                .eq(JbCustomerFastSearch::getId, id)
                .set(JbCustomerFastSearch::getTopUpTime, new Date())));
    }
    /**
     * 快速设置天取消置顶
     */
    @ApiOperation("快速设置天取消置顶")
//    @PreAuthorize("@ss.hasPermi('customer:fastTopUp')")
    @Log(title = "快速设置天取消置顶", businessType = BusinessType.UPDATE)
    @PutMapping("/cancelFastTopUp/{id}")
    public AjaxResult cancelFastTopUp(@PathVariable("id") Long id)
    {
        return success(jbCustomerFastSearchService.update(Wrappers.lambdaUpdate(JbCustomerFastSearch.class)
                .eq(JbCustomerFastSearch::getId, id)
                .set(JbCustomerFastSearch::getTopUpTime, null)));
    }

    /**
     * 查询设置快速详细
     */
    @ApiOperation("查询设置快速详细")
//    @PreAuthorize("@ss.hasPermi('customer:fastSearchInfo')")
    @GetMapping("/fastSearchInfo/{id}")
    public AjaxResult fastSearchInfo(@PathVariable("id") Long id)
    {
        return success(service.fastSearchInfo(id));
    }

    /**
     * 模版下载
     *
     * @param response
     * @param page
     * @param jbRawMaterialPrice
     */
    @Log(title = "模版下载", businessType = BusinessType.IMPORT)
    @PostMapping("/templateDownload")
    public void templateDownload(HttpServletResponse response, PageParam page, JbOpportunity jbRawMaterialPrice)
    {
        List<JbCustomerExcle> list = Lists.newArrayList();
        ExcelUtil<JbCustomerExcle> util = new ExcelUtil<JbCustomerExcle>(JbCustomerExcle.class);
        util.exportExcel(response, list, "客户模版");
    }

    /**
     * 客户导入
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "客户导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<JbCustomerExcle> util = new ExcelUtil<>(JbCustomerExcle.class);
        List<JbCustomerExcle> list = util.importExcel(file.getInputStream());
        boolean b = false;
        if (ObjectUtils.isNotEmpty(list))
        {
            b = service.importData(list);
        }
        return toAjax(b);
    }
    @ApiOperation("移入公海")
    @Log(title = "移入公海", businessType = BusinessType.UPDATE)
    @PutMapping("/transferHighSeas")
    public AjaxResult transferHighSeas(@RequestBody JbCustomerTransferDto jbCustomerTransferDto)
    {
        long count = service.count(Wrappers.lambdaQuery(JbCustomer.class)
                .eq(JbCustomer::getDataType, Constants.PUBLIC_NUMBER_0)
                .in(JbCustomer::getId, jbCustomerTransferDto.getIds()));
        if (count==0){
            return error("此客户已经操作！");
        }
        //主管以上，转移到公司公海，以下部门公海
        jbCustomerTransferDto.setDataType(Constants.PUBLIC_NUMBER_1);
        jbCustomerTransferDto.setDataTypeTime(new Date());
        SysUser user = getLoginUser().getUser();
        if (!SecurityUtils.hasRole(RoleEnum.ADMIN.getCode()))
        {
            if (ObjectUtils.isEmpty(user.getRoleIds()) || SecurityUtils.hasRole(RoleEnum.MANAGER.getCode())
                    || SecurityUtils.hasRole(RoleEnum.GROUPLEADER.getCode())
                    || SecurityUtils.hasRole(RoleEnum.COMMON.getCode()))
            {
                jbCustomerTransferDto.setDataType(Constants.PUBLIC_NUMBER_2);
                jbCustomerTransferDto.setDataTypeTime(new Date());
            }
        }
        return toAjax(service.transferHighSeas(jbCustomerTransferDto));
    }
}
